//
//  AllViewController.m
//  Gegeda_music_MY
//
//  Created by lanou3g on 15/11/2.
//  Copyright © 2015年 周莹. All rights reserved.
//

#import "AllViewController.h"
#import "Colours.h"
#import "SingerAnd3DViewCell.h"
#import "TRHTTPTool.h"
#import "AllSingerModel.h"
#import "AllSingerParam.h"
#import "AllSingerResult.h"
#import "MJExtension.h"
#import "UIImageView+WebCache.h"
#import "SingerAnd3DViewController.h"
#import "ChineseToPinyin.h"
#import "NSString+FirstChar.h"
#import "DetailViewController.h"


@interface AllViewController ()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,strong)UITableView * mainTableView;
@property(nonatomic,strong)NSMutableArray * models;
@property(nonatomic,strong)AllSingerModel * model;
@property(nonatomic,retain)NSMutableDictionary *dict;
@property(nonatomic,strong)NSMutableArray * array;
@end

static NSString * cell_id = @"cell";

@implementation AllViewController

-(NSMutableArray *)models
{
    if (!_models) {
        _models = [NSMutableArray array];
    }
    return _models;
}
-(NSMutableArray *)array
{
    if (!_array) {
        _array = [NSMutableArray array];
    }
    return _array;
}
-(NSMutableDictionary *)dict
{
    if (!_dict) {
        _dict = [NSMutableDictionary dictionary];
    }
    return _dict;
}

-(UITableView *)mainTableView
{
    if (!_mainTableView) {
        _mainTableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
    }
    return _mainTableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    //添加tableView
    [self.view addSubview:self.mainTableView];
    
    //设置代理
    self.mainTableView.delegate = self;
    self.mainTableView.dataSource = self;
    
    //tableView背景颜色
    self.mainTableView.backgroundColor = [UIColor colorWithRed:255.0/255 green:222.0/255 blue:249.0/255 alpha:1.0];
    
    self.mainTableView.sectionIndexBackgroundColor = [UIColor clearColor];
    
    [self downLoadGiftDataFinished:^{
        [self.mainTableView reloadData];
    }];
    
    //注册
//    [self.mainTableView registerClass:[SingerAnd3DViewCell class] forCellReuseIdentifier:cell_id];
    [self.mainTableView registerNib:[UINib nibWithNibName:@"SingerAnd3DViewCell" bundle:nil] forCellReuseIdentifier:cell_id];
}

//-(void)loadData
//{
//    
//}

-(void)downLoadGiftDataFinished:(void(^)())result
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSURL * url = [[NSURL alloc] init];
        if (self.index == 0) {
            url = [NSURL URLWithString:AllSingers];
        }else if (self.index == 1) {
            url = [NSURL URLWithString:Japan];
        }else if (self.index == 2) {
            url = [NSURL URLWithString:American];
        }else if (self.index == 3) {
            url = [NSURL URLWithString:Chinese];
        }else if (self.index == 4) {
            url = [NSURL URLWithString:Korea];
        }else if (self.index == 5) {
            url = [NSURL URLWithString:Other];
        }else if (self.index == 6) {
            url = [NSURL URLWithString:Musician];
        }else if (self.index == 7) {
            url = [NSURL URLWithString:nil];
        }else{
            url = [NSURL URLWithString:nil];
        }
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        
        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            
            
            
            
            NSDictionary *resultDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            NSDictionary *giftDict = resultDict[@"data"];
            NSArray *giftArray = giftDict[@"artists"];
            
            for (NSDictionary *dict in giftArray)
            {
                AllSingerModel *model = [[AllSingerModel alloc]init];
                
                [model setValuesForKeysWithDictionary:dict];
                
                //  NSLog(@"%@",giftModel1.name);
                //   [self.nameArray addObject:giftModel1.name];
                [self.models addObject:model];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                
                result();
            });
            
        }];
        
    });
    
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 28;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.models.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //新建自定义cell
    SingerAnd3DViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cell_id forIndexPath:indexPath];
    //cell背景色
    cell.backgroundColor = [UIColor colorWithRed:255.0/255 green:222.0/255 blue:249.0/255 alpha:1.0];
    //新建模型并赋值
    self.model = self.models[indexPath.row];
    //给cell赋值
    cell.nameLabel.text = self.model.artist_name;
    cell.detailLabel.text = [NSString stringWithFormat:@"%@",self.model.count_likes];
    //剪切图片地址
    NSArray * array = [self.model.artist_logo componentsSeparatedByString:@"@"];
    [cell.iconImage sd_setImageWithURL:[NSURL URLWithString:array.firstObject]];
    
    return cell;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}

-(void)addModelToAddressBook:(AllSingerModel * )model
{
    NSString * pinyinName = nil;
    NSString * groupName = nil;
    if ((([model.artist_name substringToIndex:1] >= 65) && ([model.artist_name substringToIndex:1] <= 106)) || (([model.artist_name substringToIndex:1] >= 97) && ([model.artist_name substringToIndex:1] <= 122))) {
        //获取首字母    分组名
        groupName = [NSString getFirstCharOfString:model.artist_name];
    }else{
        //拿到汉字姓名的拼音
        pinyinName = [ChineseToPinyin pinyinFromChiniseString:model.artist_name];
        //获取首字母    分组名
        groupName = [NSString getFirstCharOfString:pinyinName];
    }
    //拿出字典里所有KEY值(代表的是分组名)
    NSArray *keysArray = [self.dict allKeys];
    
    //判断groupname是否已经存在
    if([keysArray containsObject:groupName]){
        
        //如果包含
        //拿出对应的value值   即数组
        NSMutableArray *modelArray = [self.dict objectForKey:groupName];
        //把联系人添加到数组
        [modelArray addObject:model];
    }
}


#pragma mark设置分区的名字
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    self.array = [NSMutableArray arrayWithCapacity:28];
    self.array[0] = @"热门";
    for (int i = 1; i < 27; i++) {
        NSString *str =[NSString stringWithFormat:@"%c",64 + i];
        [self.array addObject:str];
    }
    self.array[27] = @"#";
    return self.array[section];
    
}

#pragma mark 设置索引
-(NSArray*)sectionIndexTitlesForTableView:(UITableView *)tableView
{
//    NSMutableArray *array = [NSMutableArray arrayWithCapacity:28];
//    array[0] = @"热门";
//    for (int i = 1; i < 27; i++) {
//        NSString *str =[NSString stringWithFormat:@"%c",64 + i];
//        [array addObject:str];
//    }
//    array[27] = @"#";
    return self.array;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 375, 50)];
    label.textAlignment = NSTextAlignmentCenter;
    label.backgroundColor = [UIColor plumColor];
    label.text = self.array[section];
    return label;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DetailViewController * vc = [[DetailViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

@end
